<template>
    <div class="org-list">
      <a-row type="flex" justify="start">
        <a-col :span="6">
          <a-card title="组织结构" class="left-tree">
            <template #extra><a href="#" @click="openAddOrgDialog" v-action:add="'organization'">添加</a></template>
            <div>
              <a-tree
                :replace-fields="replaceFields"
                :tree-data="orgTreeData"
                show-line
                @select="onSelectOrg"
              >
                <template #title="{ id: treeKey, name }">
                  <a-dropdown :trigger="['contextmenu']">
                    <span>{{ name }}</span>
                    <template #overlay>
                      <a-menu @click="({ key: menuKey }) => onContextMenuClick(treeKey, menuKey)">
                        <a-menu-item key="edit" v-action:edit="'organization'">编辑</a-menu-item>
                        <a-menu-item key="delete" v-action:delete="'organization'">删除</a-menu-item>
                      </a-menu>
                    </template>
                  </a-dropdown>
                </template>
              </a-tree>
            </div>

          </a-card>
        </a-col>
        <a-col :span="18">
          <a-card  class="right-table">
            <a-tabs default-active-key="userList">
              <a-tab-pane key="userList" tab="用户列表">
                <div class="user-list-header">
                  <a-space>
                    <a-button type="default" @click="deleteUser" v-action:users="'organization'">批量删除</a-button>
                    <a-button type="primary" @click="openAddUserDialog" v-action:users="'organization'">批量添加</a-button>
                  </a-space>
                </div>
                <!-- 表格 -->
                <a-table
                  rowKey="id"
                  :columns="columns"
                  :data-source="orgUserTableData"
                  :pagination="paginationConfig"
                  :row-selection="rowSelection"
                  @change="onChangeUserListTable"
                >
                </a-table>
              </a-tab-pane>
              <a-tab-pane key="datasourcePermissionConfig" tab="数据源权限配置">
                <div class="user-list-header">
                  <a-space>
                    <a-button type="primary" @click="openDatasourcePermissionModal('add')" v-action:project="'organization'">添加数据源权限</a-button>
                  </a-space>
                </div>
                <!-- 表格 -->
                <a-table
                  rowKey="id"
                  :columns="permissionColumns"
                  :data-source="orgPermissionData"
                  :pagination="permissionPaginationConfig"
                  @change="onChangePermissionListTable"
                >
                  <span slot="action" slot-scope="record">
                    <a @click="openDatasourcePermissionModal('edit',record)" v-action:project="'organization'">编辑</a>
                    <a-divider type="vertical"/>
                    <a @click="confirmDeletePermissionModal(record)" v-action:project="'organization'">删除</a>
                  </span>
                </a-table>
              </a-tab-pane>
            </a-tabs>

          </a-card>
        </a-col>
      </a-row>
      <a-modal
        :title="addOrEditOrgForm.title"
        :visible="addOrEditOrgForm.visible"
        :confirm-loading="addOrEditOrgForm.loading"
        :maskClosable="false"
        @ok="onSubmitAddOrEditOrg"
        @cancel="onCloseAddOrEditOrg"
      >
        <a-form-model
          ref="addOrEditOrgForm"
          :model="addOrEditOrgForm.data"
          :rules="addOrEditOrgForm.rules"
          :label-col="{ span: 4 }"
          :wrapper-col="{ span: 20 }"
        >
          <a-form-model-item label="上级组织" v-if="addOrEditOrgForm.action === 'add'">
            <a-tree-select
              v-model="addOrEditOrgForm.data.parent"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="orgTreeData"
              :replace-fields="replaceFields"
              placeholder="请选择上级组织"
              tree-default-expand-all
            >
            </a-tree-select>
          </a-form-model-item>
          <a-form-model-item label="名称" prop="name">
            <a-input v-model="addOrEditOrgForm.data.name" placeholder="请输入组织机构名称" />
          </a-form-model-item>
          <a-form-model-item label="备注" prop="remark">
            <a-input v-model="addOrEditOrgForm.data.remark" type="textarea" placeholder="请输入备注信息" />
          </a-form-model-item>
        </a-form-model>
      </a-modal>
      <a-modal
        :title="addUserForm.title"
        :visible="addUserForm.visible"
        :confirm-loading="addUserForm.loading"
        :maskClosable="false"
        @ok="onSubmitAddUser"
        @cancel="onCloseAddUser"
      >
        <a-form-model
          ref="addUserForm"
          :model="addUserForm.data"
          :rules="addUserForm.rules"
          :layout="addUserForm.layout"
        >
          <!-- 角色名称 -->
          <a-form-model-item label="" prop="userIds">
            <a-select
              mode="multiple"
              placeholder="请选择用户"
              v-model="addUserForm.data.userIds"
              style="width: 100%"
              >
              <a-select-option v-for="(item,index) in dropdownUserList" :key="item.id" :value="item.id" :disabled="item.disabled">
                {{ item.username }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-form-model>
      </a-modal>


      <datasource-permission-config
        v-bind:form="permissionForm"
        v-bind:datasourceList="datasourceList"
        v-on:refreshPermissionList="refreshPermissionList"
      ></datasource-permission-config>
    </div>
</template>

<script>
  import { mapActions, mapMutations, mapState } from 'vuex'
  import datasourcePermissionConfig from "@/views/org/components/datasourcePermissionConfig";
  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '手机',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '创建时间',
      key: 'createdAt',
      dataIndex: 'createdAt',
    },
  ];
  const permissionColumns = [
    {
      title: '数据源名称',
      key: 'datasourceName',
      dataIndex: 'datasourceName',
    },
    {
      title: '说明',
      key: 'remark',
      dataIndex: 'remark',
      width: 100
    },
    {
      title: '创建时间',
      key: 'createdAt',
      dataIndex: 'createdAt',
    },
    {
      title: '更新时间',
      key: 'updatedAt',
      dataIndex: 'updatedAt',
    },
    {
      title: '操作',
      fixed: 'right',
      scopedSlots: { customRender: 'action' }
    }
  ];

  export default {
    name: 'organizationList',
    components: { datasourcePermissionConfig },
    data() {
      return {
        columns,
        permissionColumns,
        addOrEditOrgForm: {
          action: 'add',
          title: '',
          visible: false,
          loading: false,
          data: {
            parent: null,
            name: "",
            remark: "",
          },
          rules: {
            name: [
              {
                required: true,
                trigger: 'blur',
                message: '请输入组织机构名称'
              },
              {
                max: 100,
                trigger: 'blur',
                message: '组织机构名称不能超出100个字符'
              }
            ],
            remark: [
              {
                max: 255,
                trigger: 'blur',
                message: '备注不能超出255个字符'
              }
            ]
          },

        },
        addUserForm: {
          layout: 'vertical',
          title: '添加用户',
          visible: false,
          loading: false,
          data: {
            userIds: []
          },
          rules: {
            userIds: [
              {
                type: 'array',
                required: true,
                trigger: 'change',
                message: '请选择用户'
              }
            ]
          },

        },
        selectedOrgId: null,
        selectedUsers: [],
        permissionForm: this.getDefaultPermissionForm(),
        orgPermissionData:[],
        datasourceList:[]
      };
    },
    computed: {
      ...mapState('orgManage',['orgTreeData', 'replaceFields', 'orgUserTableData', 'orgUserList','paginationConfig', 'allUsers', 'permissionPaginationConfig']),
      rowSelection() {
        return {
          selectedRowKeys: this.selectedUsers,
          onChange: (selectedRowKeys, selectedRows) => {
            this.selectedUsers = selectedRowKeys
          }
        };
      },
      dropdownUserList() {
        let userList = [];
        for(let i = 0; i < this.allUsers.length; i++) {
          let user = this.allUsers[i];
          let matchedIndex = this.orgUserTableData.findIndex((item, index) => {
            return item.id === user.id
          })
          if(matchedIndex != -1) {
            user['disabled'] = true
          } else {
            user['disabled'] = false
          }
          userList.push(user)
        }
        return userList;
      }
    },
    methods: {
      ...mapMutations('orgManage', ['setOrgTreeData', 'setOrgUserTableData', 'setOrgUserList', 'setSelectedUsers', 'setPage', 'setPageSize', 'setOrder', 'setOrderBy']),
      ...mapActions('orgManage', ['getOrgData', 'getOrgUserList', 'getAllUsersList', 'addOrgUsers', 'removeOrgUsers', 'addOrg', 'modifyOrg', 'removeOrg', 'getPermissionListByOrgId', 'removeOrgPermission']),
      ...mapActions('dataManage', ['getAllDatasourceList']),
      onSelectOrg(selectedKeys, info) {
        this.selectedUsers = [];
        this.resetAddUserForm();
        if (selectedKeys.length > 0){
          this.selectedOrgId = selectedKeys[0];
          this.getOrgUserList(this.selectedOrgId);
          this.getPermissionData(this.selectedOrgId)
        }else {
          this.selectedOrgId = null
          this.orgPermissionData = []
        }
      },
      onContextMenuClick(treeKey, menuKey) {
        if (!this.selectedOrgId || treeKey !== this.selectedOrgId){
          this.$message.error('请先选中要操作的组织机构')
          return
        }
        let orgId = treeKey
        if(menuKey === 'edit') {
          this.openEditOrgDialog(orgId)
        } else if(menuKey === 'delete') {
          this.deleteOrg(orgId)
        }
      },
      openAddOrgDialog() {
        this.addOrEditOrgForm.action = 'add'
        this.addOrEditOrgForm.title = '添加组织机构'
        this.addOrEditOrgForm.data.parent = this.selectedOrgId
        this.addOrEditOrgForm.visible = true
      },
      getOrgById(orgId, orgData) {
        let org = null
        for(let i = 0; i < orgData.length; i++) {
          if (orgData[i].id === orgId) {
            org = orgData[i]
            break
          }
          org = this.getOrgById(orgId, orgData[i].children)
          if(org !== null) {
            break
          }
        }
        return org
      },
      openEditOrgDialog(orgId) {
        this.addOrEditOrgForm.action = 'edit'
        this.addOrEditOrgForm.title = '编辑组织机构'
        let org = this.getOrgById(orgId, this.orgTreeData)
        this.addOrEditOrgForm.data.name = org.name
        this.addOrEditOrgForm.data.remark = org.remark
        this.addOrEditOrgForm.visible = true
      },
      deleteOrg(orgId) {
        this.$confirm({
          title: '删除提示',
          content: '您确定要删除该组织吗？',
          okText: '确定',
          cancelText: '取消',
          onOk: () => {
            this.removeOrg(this.selectedOrgId)
              .then((res)=>{
                this.$message.success('删除组织成功')
                this.selectedOrgId = null
                this.getOrgData()
              })
              .catch((err) => {
                this.$message.error('删除组织失败，原因：' + err.msg + '！')
              })
          },
          onCancel: () => {},
        })
      },
      onSubmitAddOrEditOrg() {
        this.$refs.addOrEditOrgForm.validate(valid => {
          if (valid) {
            if(this.addOrEditOrgForm.action === 'add') {
              this.addOrEditOrgForm.loading = true
              let params = {
                parent: this.addOrEditOrgForm.data.parent ? this.addOrEditOrgForm.data.parent : 0,
                name: this.addOrEditOrgForm.data.name,
                remark: this.addOrEditOrgForm.data.remark
              }
              this.addOrg(params)
                .then(res => {
                  this.$message.success('添加组织成功')
                  this.addOrEditOrgForm.visible = false
                  this.getOrgData()
                }).catch(error => {
                  this.$message.error('添加组织失败，原因：' + error.msg)
                }).finally(()=>{
                  this.addOrEditOrgForm.loading = false
                })
            } else if(this.addOrEditOrgForm.action === 'edit') {
              this.addOrEditOrgForm.loading = true
              let params = {
                orgId: this.selectedOrgId,
                data: {
                  name: this.addOrEditOrgForm.data.name,
                  remark: this.addOrEditOrgForm.data.remark
                }
              }
              this.modifyOrg(params)
                .then(res => {
                  this.$message.success('修改组织成功')
                  this.addOrEditOrgForm.visible = false
                  this.getOrgData()
                }).catch(error => {
                  this.$message.error('修改组织失败，原因：' + error.msg)
                }).finally(()=>{
                  this.addOrEditOrgForm.loading = false
                })
            }
          }
        })
      },
      onCloseAddOrEditOrg() {
        this.addOrEditOrgForm.visible = false
        this.resetAddOrEditOrgForm()
      },
      resetAddOrEditOrgForm() {
        this.addOrEditOrgForm.data.parent = null
        this.addOrEditOrgForm.data.name = ''
        this.addOrEditOrgForm.data.remark = ''
      },
      openAddUserDialog() {
        this.getAllUsersList()
        this.addUserForm.visible = true
      },
      onSubmitAddUser() {
        if (!this.selectedOrgId){
          this.$message.error('必须先选择一个组织')
          return
        }
        this.$refs.addUserForm.validate(valid => {
          if (valid) {
            this.addUserForm.loading = true;
            let params = {
              orgId: this.selectedOrgId,
              userIds: this.addUserForm.data.userIds
            }
            this.addOrgUsers(params)
              .then(res => {
                this.$message.success('添加用户成功')
                this.addUserForm.visible = false
                this.setPage(1)
                this.setPageSize(10)
                this.getOrgUserList(this.selectedOrgId)
              }).catch(error => {
                this.$message.error('添加用户失败，原因：' + error.msg)
              }).finally(()=>{
                this.addUserForm.loading = false
            })
          }
        })
      },
      onCloseAddUser() {
        this.addUserForm.visible = false
        this.resetAddUserForm()
      },
      resetAddUserForm() {
        this.addUserForm.data.userIds = []
      },
      deleteUser() {
        if(this.selectedUsers.length === 0) {
          this.$message.info('请选择要删除的用户')
        } else {
          this.$confirm({
            title: '删除提示',
            content: '您确定要移除用户吗？',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
              let params = {
                orgId: this.selectedOrgId,
                userIds: this.selectedUsers
              }
              this.removeOrgUsers(params)
                .then((res)=>{
                  this.$message.success('移除用户成功')
                  this.getOrgUserList(this.selectedOrgId);
                })
                .catch((err) => {
                  this.$message.error('移除用户失败，原因：' + err.msg + '！')
                })
            },
            onCancel: () => {},
          })
        }
      },
      openDatasourcePermissionModal(type,record) {
        if (!this.selectedOrgId){
          this.$message.error('请先选择组织机构')
          return
        }
        this.permissionForm = this.getDefaultPermissionForm()
        if (type === 'add'){
          this.permissionForm.title = '添加项目权限'
        }else if (type === 'edit'){
          this.permissionForm.title = '编辑项目权限'
          let data = JSON.parse(JSON.stringify(record))
          data.config = JSON.parse(data.config)
          this.permissionForm.data = data
        }
        this.permissionForm.visible = true
        this.permissionForm.type = type

      },
      confirmDeletePermissionModal (record) {
        this.$confirm({
          title: '删除提示',
          content: '您确定要删除该数据源权限吗？',
          okText: '确定',
          cancelText: '取消',
          onOk: () => {
            this.removeOrgPermission({orgId: record.orgId, datasourceId: record.datasourceId})
              .then((res)=>{
                this.$message.success('删除数据源权限成功')
                this.refreshPermissionList()
              })
              .catch((err) => {
                this.$message.error('删除数据源权限失败，原因：' + err.msg + '！')
              })
          },
          onCancel: () => {},
        })
      },
      onChangeUserListTable(pagination, filters) {
        this.setPage(pagination.current)
        this.setPageSize(pagination.pageSize)
        this.getOrgUserList(this.selectedOrgId)
      },
      onChangePermissionListTable(pagination) {
        this.setPermissionTablePage(pagination.current)
        this.setPermissionTablePageSize(pagination.pageSize)
        this.getPermissionData(this.selectedOrgId)
      },
      getDefaultPermissionForm () {
        return {
          title: "",
          visible: false,
          loading: false,
          orgId: this.selectedOrgId,
          data: {
            config: {
              condition: 'AND',
              rules: []
            }
          }
        }
      },
      refreshPermissionList(){
        this.getPermissionData(this.selectedOrgId)
      },
      getPermissionData(orgId) {
        if (!orgId) {
          return
        }
        this.getPermissionListByOrgId({ orgId:orgId }).then(res =>{
          this.orgPermissionData = res
        }).catch((err) => {
          this.$message.error('获取组织机构权限列表失败，原因：' + err.msg + '！')
        })
      },
      getDatasourceData() {
        this.getAllDatasourceList().then(res =>{
          this.datasourceList = res.data.data
        }).catch((err) => {
          this.$message.error('获取项目列表失败，原因：' + err.msg + '！')
        })
      },
      initPageData (){
        this.getOrgData()
        this.setOrder("desc")
        this.setOrderBy("createdAt")
        this.getDatasourceData()
      }
    },
    mounted() {
      this.initPageData()
    },

  }
</script>

<style scoped>
  .org-list {
    width: 100%;
    height: 100%;
  }
  .left-tree {
    min-height: 400px;
    margin-bottom: 20px;
  }
  .right-table {
    width: 100%;
    min-height: 400px;
  }
  .user-list-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
  .user-list-header .title {
    display: block;
    float: left;
    margin-bottom: 0;
    padding-right: 12px;
    color: rgba(0,0,0,.85);
    font-weight: 500;
    font-size: 16px;
    line-height: 32px;
  }
  .org-list >>> ul.ant-pagination.ant-table-pagination {
    width: 100%;
    display: flex;
  }

  .org-list >>> ul.ant-pagination.ant-table-pagination>li.ant-pagination-total-text {
    flex: 1;
    text-indent: 10px;
    font-size: 14px;
    color: #999;
  }

  .org-list >>> .ant-table-body { white-space: nowrap; }
</style>
